package com.example.chuntiao.cophook.ui;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.example.chuntiao.cophook.R;
import com.example.chuntiao.cophook.exception.RepeatException;
import com.example.chuntiao.cophook.mytools.HttpTool;

import java.io.IOException;

public class NewOrgActivity extends AppCompatActivity {

    ImageView imgOrgPhoto;
    LinearLayout layoutDone;
    EditText editOname;
    EditText editIntro;
    static final int REQ_FOR_CHOOSE_ACTI = 0;
    static final int REQ_FRO_crop = 1;
    Bitmap bitmap;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case REQ_FOR_CHOOSE_ACTI:
                if (resultCode == RESULT_OK) {
                    Uri uri = null;
                    if (data != null) {
                        uri = data.getData();
                        cropPhoto(uri);
                    }
                }
                break;
            case REQ_FRO_crop:
                if (resultCode == RESULT_OK) {

                    Bundle bundle = data.getExtras();
                    bitmap = bundle.getParcelable("data");
                    imgOrgPhoto.setImageBitmap(bitmap);
                }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_org);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        imgOrgPhoto = (ImageView) findViewById(R.id.img_org_photo);

        layoutDone = (LinearLayout) findViewById(R.id.layout_done);
        editIntro = (EditText) findViewById(R.id.edit_intro);
        editOname = (EditText) findViewById(R.id.edit_oname);

        Glide.with(NewOrgActivity.this)
                .load(R.drawable.hello)
                .transition(new DrawableTransitionOptions().crossFade())
                .into(imgOrgPhoto);

        layoutDone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("".equals(editOname)) {
                    Snackbar.make(layoutDone, "qingba", Snackbar.LENGTH_SHORT).show();
                    return;
                }

                final String oname = editOname.getText().toString();
                final String intro = editIntro.getText().toString();


                new AsyncTask<Void, Void, Boolean>() {

                    ProgressDialog dialog;
                    AlertDialog alert;

                    @Override
                    protected void onPreExecute() {
                        dialog = ProgressDialog.show(NewOrgActivity.this, null, "创建中");
                        alert = new AlertDialog.Builder(NewOrgActivity.this)
                                .setMessage("未知错误")
                                .setPositiveButton(R.string.yse, null)
                                .create();
                    }

                    @Override
                    protected Boolean doInBackground(Void... params) {
                        String oid = null;
                        try {
                            oid = HttpTool.sendOkHttpNewOrg(NewOrgActivity.this, oname, intro);
                            if (oid != null && bitmap != null) {
                                int imgVer = HttpTool.sendOkHttpUpload(NewOrgActivity.this, bitmap, HttpTool.UPLOAD_OEG_IMG, oid);
                            }
                            return true;
                        } catch (RepeatException e) {
                            e.printStackTrace();
                            alert.setMessage("系统繁忙，稍后重试");
                        } catch (IOException e) {
                            e.printStackTrace();
                            if (oid != null) {
                                alert.setMessage("组织创建完成，照片上传失败，请在 侧栏 “管理“，重新上传");
                                alert.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        finish();
                                    }
                                });
                            }

                        }
                        return false;
                    }

                    @Override
                    protected void onPostExecute(Boolean result) {
                        dialog.dismiss();
                        dialog = null;
                        if (!result) {
                            alert.show();
                        } else {
                            setResult(RESULT_OK);
                            finish();
                        }
                    }
                }.execute();

            }
        });

        imgOrgPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(
                        Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
                startActivityForResult(intent, REQ_FOR_CHOOSE_ACTI);
            }
        });
    }

    private void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", true);
        intent.putExtra("aspectX", 2.2);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 330);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, REQ_FRO_crop);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId()== android.R.id.home){
            super.onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
